package main

import (
	"awesomeProject1/server"
	"awesomeProject1/server/backend"
	"fmt"
	"github.com/simplechain-org/client/log"
	"github.com/urfave/cli"
	"os"
	"os/signal"
	"runtime"
	"syscall"
	"time"
)

const VERSION = "v1.0.1"
const NAME = "haha"

func main() {
	//gin.SetMode(gin.ReleaseMode)
	runtime.GOMAXPROCS(runtime.NumCPU())

	app := cli.NewApp()
	app.Name = NAME
	app.Version = VERSION
	configFlag := cli.StringFlag{
		Name:   "config",
		Usage:  "config file path",
		EnvVar: "config",
		Value:  "./config/config.yaml",
	}
	serverTypeFlag := cli.StringFlag{
		Name:   "type",
		Usage:  "server type, e.g. backend、producer、consumer",
		EnvVar: "type",
	}
	syncDataFlag := cli.BoolFlag{
		Name:   "disable-sync",
		Usage:  "not to sync chain data (default false)",
		EnvVar: "disable-sync",
	}

	app.Flags = []cli.Flag{
		configFlag,
		serverTypeFlag,
		syncDataFlag,
	}
	app.Action = Start
	app.Commands = []cli.Command{
		versionCommand,
	}
	err := app.Run(os.Args)
	if err != nil {
		log.Error(err.Error())
		os.Exit(1)
	}
}

func logVersion() {
	log.Info(fmt.Sprintf("gitCommit:%s", gitCommit))
	log.Info(fmt.Sprintf("gitDate:%s", gitDate))
	log.Info(fmt.Sprintf("buildDate:%s", buildDate))
}

func Start(ctx *cli.Context) error {
	sigCh := make(chan os.Signal)
	defer close(sigCh)
	signal.Notify(sigCh, syscall.SIGINT, syscall.SIGKILL, syscall.SIGTERM)

	configPath := ctx.String("config")
	serverType := ctx.String("type")
	disableSyncData := ctx.Bool("disable-sync")
	logVersion()
	// 打印启动信息
	log.WelcomeLog(NAME, VERSION)
	log.Info(fmt.Sprintf("config: %s, type: %s, disable-sync: %t", configPath, serverType, disableSyncData))

	var backendServer server.Server

	backendServer = backend.New(NAME)

	go func() {
		select {
		case <-sigCh:
			if err := backendServer.Close(); err != nil {
				log.Error(err.Error())
			}
			time.Sleep(time.Second)
			log.ExitLog(NAME, VERSION)
			os.Exit(0)
		}
	}()
	err := backendServer.Run(configPath)

	if err != nil {
		return err
	}
	return nil
}
